{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 经典排序算法总结\n",
    "> 所谓排序，就是使一串记录，按照其中的某个或某些关键字的大小，递增或递减的排列起来的操作。排序算法，就是如何使得记录按照要求排列的方法。排序算法在很多领域得到相当地重视，尤其是在大量数据的处理方面。一个优秀的算法可以节省大量的资源。在各个领域中考虑到数据的各种限制和规范，要得到一个符合实际的优秀算法，得经过大量的推理和分析。\n",
    "\n",
    "### 评价标准\n",
    "* 时间复杂度：即从序列的初始状态到经过排序算法的变换移位等操作变到最终排序好的结果状态的过程所花费的时间度量。\n",
    "* 稳定性：描述算法对原始序列处理前后，该序列相等大小的元素前后位置是否发生改变\n",
    "* 空间复杂度：就是从序列的初始状态经过排序移位变换的过程一直到最终的状态所花费的空间开销。\n",
    "\n",
    "### 常用排序算法\n",
    "[![namkGV.md.png](https://s2.ax1x.com/2019/09/10/namkGV.md.png)](https://imgchr.com/i/namkGV)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 冒泡排序\n",
    "\n",
    "> 冒泡排序是一种简单的排序算法。它重复地走访过要排序的数列，一次比较两个元素，如果它们的顺序错误就把它们交换过来。走访数列的工作是重复地进行直到没有再需要交换，也就是说该数列已经排序完成。这个算法的名字由来是因为越小的元素会经由交换慢慢“浮”到数列的顶端。\n",
    "### 算法描述\n",
    "* 比较相邻的元素。如果第一个比第二个大，就交换它们两个；\n",
    "* 对每一对相邻元素作同样的工作，从开始第一对到结尾的最后一对，这样在最后的元素应该会是最大的数；\n",
    "\n",
    "* 针对所有的元素重复以上的步骤，除了最后一个；\n",
    "\n",
    "* 重复步骤1~3，直到排序完成。\n",
    "\n",
    "\n",
    "### 动图演示\n",
    "![naAQeI.gif](https://s2.ax1x.com/2019/09/10/naAQeI.gif)\n",
    "### 视频讲解\n",
    "https://www.bilibili.com/video/av18176281"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {
    "code_folding": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 6]"
      ]
     },
     "execution_count": 31,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def bubble_sort(arr):\n",
    "    Len = len(arr)\n",
    "    for i in range(Len-1):\n",
    "        for j in range(Len-i-1):\n",
    "            if arr[j] > arr[j+1]:\n",
    "                arr[j],arr[j+1] = arr[j+1],arr[j]\n",
    "    return arr\n",
    "\n",
    "arr = [3,2,4,1,6]\n",
    "bubble_sort(arr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 选择排序\n",
    "\n",
    "> 选择排序提高了冒泡排序的性能，它每遍历一次列表只交换一次数据，即进行一次遍历时找 到最大的项，完成遍历后，再把它换到正确的位置。和冒泡排序一样，第一次遍历后，最大的数 据项就已归位，第二次遍历使次大项归位。这个过程持续进行，一共需要 n-1 次遍历来排好 n 个数 据，因为最后一个数据必须在第 n-1 次遍历之后才能归位。\n",
    "\n",
    "### 算法描述\n",
    "* 在未排序序列中找到最小（大）元素，存放到排序序列的起始位置\n",
    "\n",
    "* 从剩余未排序元素中继续寻找最小（大）元素，然后放到已排序序列的末尾。\n",
    "\n",
    "* 重复第二步，直到所有元素均排序完毕。\n",
    "\n",
    "### 动图演示\n",
    "\n",
    "\n",
    "![nannl8.gif](https://s2.ax1x.com/2019/09/10/nannl8.gif)\n",
    "### 视频讲解\n",
    "https://www.bilibili.com/video/av18176082"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 6]"
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def selection_sort(arr):\n",
    "    Len = len(arr)\n",
    "    for i in range(Len-1):\n",
    "        min_index = i\n",
    "        for j in range(i+1,Len):\n",
    "            if arr[min_index] > arr[j]:\n",
    "                arr[j],arr[min_index] = arr[min_index],arr[j]\n",
    "    return arr\n",
    "\n",
    "arr = [3,2,4,1,6]\n",
    "selection_sort(arr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 插入排序"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 直接插入排序\n",
    " \n",
    "> 插入排序是一种简单直观的排序算法。它的工作原理是通过构建有序序列，对于未排序数据，在已排序序列中从后向前扫描，找到相应位置并插入。\n",
    "\n",
    "### 算法描述\n",
    "* 把待排序的数组分成已排序和未排序两部分，初始的时候把第一个元素认为是已排好序的。\n",
    "\n",
    "* 从第二个元素开始，在已排好序的子数组中寻找到该元素合适的位置并插入该位置。\n",
    "\n",
    "* 重复上述过程直到最后一个元素被插入有序子数组中。\n",
    "\n",
    "### 动图演示\n",
    "![nanlwj.gif](https://s2.ax1x.com/2019/09/10/nanlwj.gif)\n",
    "### 视频讲解\n",
    "https://www.bilibili.com/video/av18980488"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 6]"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def insertion_sort(arr):\n",
    "    Len = len(arr)\n",
    "    for i in range(1,Len):\n",
    "        for j in range(i,0,-1):\n",
    "            if arr[j] < arr[j-1]:\n",
    "                arr[j],arr[j-1] = arr[j-1],arr[j]\n",
    "    return arr\n",
    "\n",
    "arr = [3,2,4,1,6]\n",
    "insertion_sort(arr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 希尔排序\n",
    " \n",
    "### 算法描述\n",
    "* 选择一个增量序列t1，t2，…，tk，其中ti>tj，tk=1；\n",
    "\n",
    "* 按增量序列个数k，对序列进行 k 趟排序；\n",
    "\n",
    "* 每趟排序，根据对应的增量ti，将待排序列分割成若干长度为m 的子序列，分别对各子表进行直接插入排序。仅增量因子为1 时，整个序列作为一个表来处理，表长度即为整个序列的长度。\n",
    "\n",
    "### 动图演示\n",
    "![nauSNn.gif](https://s2.ax1x.com/2019/09/10/nauSNn.gif)\n",
    "### 视频讲解\n",
    "https://www.bilibili.com/video/av15961896?from=search&seid=3767742559497289963"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 35,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 6]"
      ]
     },
     "execution_count": 35,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def shell_sort(arr):\n",
    "    step = len(arr)//2\n",
    "    while step > 0:\n",
    "        for i in range(step,len(arr)):\n",
    "            # 类似插入排序, 当前值与指定步长之前的值比较, 符合条件则交换位置\n",
    "            while i >= step and arr[i-step] > arr[i]:\n",
    "                arr[i], arr[i-step] = arr[i-step], arr[i]\n",
    "                i -= step\n",
    "        step = step//2\n",
    "    return arr\n",
    "\n",
    "arr = [3,2,4,1,6]\n",
    "shell_sort(arr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 快速排序\n",
    "### 算法描述\n",
    "* 从数列中挑出一个元素，称为\"基准\"（pivot），\n",
    "\n",
    "* 重新排序数列，所有比基准值小的元素摆放在基准前面，所有比基准值大的元素摆在基准后面（相同的数可以到任何一边）。在这个分区结束之后，该基准就处于数列的中间位置。这个称为分区（partition）操作。\n",
    "\n",
    "* 递归地（recursively）把小于基准值元素的子数列和大于基准值元素的子数列排序。\n",
    "### 动图演示\n",
    "![nau3uD.gif](https://s2.ax1x.com/2019/09/10/nau3uD.gif)\n",
    "### 视频讲解\n",
    "https://www.bilibili.com/video/av18980345"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "code_folding": []
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 6]"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def quick_sort(nums):\n",
    "    if len(nums) <= 1:\n",
    "        return nums\n",
    "    # 随意选取一个基准数，比如选取列表第一个数\n",
    "    base = nums[0]\n",
    "    # left列表为nums中比基准数base小或等于base的数组成的列表\n",
    "    left = [x for x in nums[1:] if x <= base]\n",
    "    # right列表为nums中比基准数base大的数组成的列表\n",
    "    right = [x for x in nums[1:] if x > base]\n",
    "    # 对left和right列表递归排序\n",
    "    return quick_sort(left) + [base] + quick_sort(right)\n",
    "\n",
    "nums = [3,2,4,1,6]\n",
    "quick_sort(nums)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 堆排序\n",
    "> 堆排序(Heapsort)是指利用堆积树（堆）这种数据结构所设计的一种排序算法，它是选择排序的一种。可以利用数组的特点快速定位指定索引的元素。堆排序就是把最大堆堆顶的最大数取出，将剩余的堆继续调整为最大堆，再次将堆顶的最大数取出，这个过程持续到剩余数只有一个时结束。\n",
    "\n",
    "### 算法描述\n",
    "* 将初始待排序关键字序列(R1,R2….Rn)构建成大顶堆，此堆为初始的无序区；\n",
    "\n",
    "\n",
    "* 将堆顶元素R[1]与最后一个元素R[n]交换，此时得到新的无序区(R1,R2,……Rn-1)和新的有序区(Rn),且满足R[1,2…n-1]<=R[n]；\n",
    "\n",
    "\n",
    "* 由于交换后新的堆顶R[1]可能违反堆的性质，因此需要对当前无序区(R1,R2,……Rn-1)调整为新堆，然后再次将R[1]与无序区最后一个元素交换，得到新的无序区(R1,R2….Rn-2)和新的有序区(Rn-1,Rn)。不断重复此过程直到有序区的元素个数为n-1，则整个排序过程完成。\n",
    "### 动图演示\n",
    "![nausbQ.gif](https://s2.ax1x.com/2019/09/10/nausbQ.gif)\n",
    "### 视频讲解\n",
    "https://www.bilibili.com/video/av18980178\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 6]"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def HeapSort(ls):\n",
    "    def heapadjust(arr,start,end):  #将以start为根节点的堆调整为大顶堆\n",
    "        temp=arr[start]\n",
    "        son=2*start+1\n",
    "        while son<=end:\n",
    "            if son<end and arr[son]<arr[son+1]:  #找出左右孩子节点较大的\n",
    "                son+=1\n",
    "            if temp>=arr[son]:       #判断是否为大顶堆\n",
    "                break\n",
    "            arr[start]=arr[son]     #子节点上移\n",
    "            start=son                     #继续向下比较\n",
    "            son=2*son+1\n",
    "        arr[start]=temp             #将原堆顶插入正确位置\n",
    "#######\n",
    "    n=len(ls)\n",
    "    if n<=1:\n",
    "        return ls\n",
    "    #建立大顶堆\n",
    "    root=n//2-1    #最后一个非叶节点（完全二叉树中）\n",
    "    while(root>=0):\n",
    "        heapadjust(ls,root,n-1)\n",
    "        root-=1\n",
    "    #掐掉堆顶后调整堆\n",
    "    i=n-1\n",
    "    while(i>=0):\n",
    "        (ls[0],ls[i])=(ls[i],ls[0])  #将大顶堆堆顶数放到最后\n",
    "        heapadjust(ls,0,i-1)    #调整剩余数组成的堆\n",
    "        i-=1\n",
    "    return ls\n",
    "\n",
    "arr = [3,2,4,1,6]\n",
    "HeapSort(arr)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 归并排序\n",
    "### 算法描述\n",
    "* 将序列每相邻两个数字进行归并操作，形成ceil(n/2)个序列，排序后每个序列包含两/一个元素\n",
    "* 若此时序列数不是1个则将上述序列再次归并，形成ceil(n/4)个序列，每个序列包含四/三个元素\n",
    "* 重复步骤2，直到所有元素排序完毕，即序列数为1\n",
    "\n",
    "### 图片演示\n",
    "[![nUJSoD.png](https://s2.ax1x.com/2019/09/10/nUJSoD.png)](https://imgchr.com/i/nUJSoD)\n",
    "### 视频讲解\n",
    "https://www.bilibili.com/video/av18980253"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[1, 2, 3, 3, 4, 8, 8, 9, 22, 65]\n"
     ]
    }
   ],
   "source": [
    "def MergerSort(lists):\n",
    "    if len(lists)<=1:\n",
    "        return lists\n",
    "    num=int(len(lists)/2)\n",
    "    left=MergerSort(lists[:num])\n",
    "    right=MergerSort(lists[num:])\n",
    "    return Merge(left,right)\n",
    "\n",
    "def Merge(left,right):\n",
    "    r,l=0,0\n",
    "    result=[]\n",
    "    while l<len(left) and r<len(right):\n",
    "        if left[l]<=right[r]:\n",
    "            result.append(left[l])\n",
    "            l+=1\n",
    "        else:\n",
    "            result.append(right[r])\n",
    "            r+=1\n",
    "    result+=list(left[l:])\n",
    "    result+=list(right[r:])\n",
    "    return result\n",
    "print(MergerSort([22,3,2,8,65,8,9,1,4,3]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 桶排序\n",
    "> 桶排序又叫箱排序，是计数排序的升级版，它的工作原理是将数组分到有限数量的桶子里，然后对每个桶子再分别排序（有可能再使用别的排序算法或是以递归方式继续使用桶排序进行排序），最后将各个桶中的数据有序的合并起来。\n",
    "\n",
    "### 算法描述\n",
    "* 找出待排序数组中的最大值max、最小值min\n",
    "\n",
    "* 我们使用 动态数组ArrayList 作为桶，桶里放的元素也用 ArrayList 存储。桶的数量为(max-min)/arr.length+1\n",
    "\n",
    "* 遍历数组 arr，计算每个元素 arr[i] 放的桶\n",
    "\n",
    "* 每个桶各自排序\n",
    "* 遍历桶数组，把排序好的元素放进输出数组\n",
    "### 动图演示\n",
    "![naKCad.gif](https://s2.ax1x.com/2019/09/10/naKCad.gif)\n",
    "### 视频讲解\n",
    "https://www.bilibili.com/video/av17940595\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[1, 2, 3, 4, 6]"
      ]
     },
     "execution_count": 18,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def bucket_sort(nums):\n",
    "    max_num = max(nums)\n",
    "    bucket = [0]*(max_num + 1)\n",
    "    for i in nums:\n",
    "        bucket[i] += 1 \n",
    "    \n",
    "    sort_nums = []\n",
    "    for i in range(len(bucket)):\n",
    "        if bucket[i] != 0:\n",
    "            for j in range(bucket[i]):\n",
    "                sort_nums.append(i)\n",
    "                \n",
    "    return sort_nums\n",
    "\n",
    "nums = [3,2,4,1,6]\n",
    "bucket_sort(nums)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 基数排序\n",
    "> 基数排序(Radix Sort)是桶排序的扩展，它的基本思想是：将整数按位数切割成不同的数字，然后按每个位数分别比较。\n",
    "排序过程：将所有待比较数值（正整数）统一为同样的数位长度，数位较短的数前面补零。然后，从最低位开始，依次进行一次排序。这样从最低位排序一直到最高位排序完成以后, 数列就变成一个有序序列。\n",
    "\n",
    "\n",
    "### 算法描述\n",
    "* 取得数组中的最大数，并取得位数；\n",
    "\n",
    "* arr为原始数组，从最低位开始取每个位组成radix数组；\n",
    "\n",
    "* 对radix进行计数排序（利用计数排序适用于小范围数的特点）；\n",
    "\n",
    "### 动图演示\n",
    "\n",
    "[![nUGfs0.gif](https://s2.ax1x.com/2019/09/10/nUGfs0.gif)](https://imgchr.com/i/nUGfs0)\n",
    "### 视频讲解\n",
    "https://www.bilibili.com/video/av18980653"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 49,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[745, 331, 655, 662, 309, 125, 627, 53, 321, 462]\n",
      "[53, 125, 309, 321, 331, 462, 627, 655, 662, 745]\n"
     ]
    }
   ],
   "source": [
    "from random import randint\n",
    " \n",
    "#利用列表的下标从小到大实现了排序\n",
    "def RadixSort(list,d):    \n",
    "    for k in range(d):#d轮排序\n",
    "        s=[[] for i in range(10)]#因为每一位数字都是0~9，故建立10个桶\n",
    "        '''对于数组中的元素，首先按照最低有效数字进行\n",
    "           排序，然后由低位向高位进行。'''\n",
    "        for i in list:\n",
    "            '''对于3个元素的数组[977, 87, 960]，第一轮排序首先按照个位数字相同的\n",
    "               放在一个桶s[7]=[977],s[7]=[977,87],s[0]=[960]\n",
    "               执行后list=[960,977,87].第二轮按照十位数，s[6]=[960],s[7]=[977]\n",
    "               s[8]=[87],执行后list=[960,977,87].第三轮按照百位，s[9]=[960]\n",
    "               s[9]=[960,977],s[0]=87,执行后list=[857,960,977],结束。'''\n",
    "            m=int(i/(10**k)%10)\n",
    "            s[m].append(i) # 977/(10**0)%10=7,s[7].append(977) ;977/10=97(小数舍去),87/100=0\n",
    "            #此处利用了S的下标的大小顺序来排列，正好关键字的大小\n",
    "            \n",
    "        list=[j for i in s for j in i]#利用了for i in s，执行时会按s中下标从0开始\n",
    "    return list\n",
    " \n",
    "if __name__ == '__main__':\n",
    "    a=[randint(1,999) for i in range(10)]#最多是三位数，因此d=3\n",
    "    print(a)\n",
    "    a=RadixSort(a,3)#将排好序的数组再赋给a!!!!\n",
    "    print(a)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 皇后问题"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0, 4, 7, 5, 2, 6, 1, 3]\n",
      "[0, 5, 7, 2, 6, 3, 1, 4]\n",
      "[0, 6, 3, 5, 7, 1, 4, 2]\n",
      "[0, 6, 4, 7, 1, 3, 5, 2]\n",
      "[1, 3, 5, 7, 2, 0, 6, 4]\n",
      "[1, 4, 6, 0, 2, 7, 5, 3]\n",
      "[1, 4, 6, 3, 0, 7, 5, 2]\n",
      "[1, 5, 0, 6, 3, 7, 2, 4]\n",
      "[1, 5, 7, 2, 0, 3, 6, 4]\n",
      "[1, 6, 2, 5, 7, 4, 0, 3]\n",
      "[1, 6, 4, 7, 0, 3, 5, 2]\n",
      "[1, 7, 5, 0, 2, 4, 6, 3]\n",
      "[2, 0, 6, 4, 7, 1, 3, 5]\n",
      "[2, 4, 1, 7, 0, 6, 3, 5]\n",
      "[2, 4, 1, 7, 5, 3, 6, 0]\n",
      "[2, 4, 6, 0, 3, 1, 7, 5]\n",
      "[2, 4, 7, 3, 0, 6, 1, 5]\n",
      "[2, 5, 1, 4, 7, 0, 6, 3]\n",
      "[2, 5, 1, 6, 0, 3, 7, 4]\n",
      "[2, 5, 1, 6, 4, 0, 7, 3]\n",
      "[2, 5, 3, 0, 7, 4, 6, 1]\n",
      "[2, 5, 3, 1, 7, 4, 6, 0]\n",
      "[2, 5, 7, 0, 3, 6, 4, 1]\n",
      "[2, 5, 7, 0, 4, 6, 1, 3]\n",
      "[2, 5, 7, 1, 3, 0, 6, 4]\n",
      "[2, 6, 1, 7, 4, 0, 3, 5]\n",
      "[2, 6, 1, 7, 5, 3, 0, 4]\n",
      "[2, 7, 3, 6, 0, 5, 1, 4]\n",
      "[3, 0, 4, 7, 1, 6, 2, 5]\n",
      "[3, 0, 4, 7, 5, 2, 6, 1]\n",
      "[3, 1, 4, 7, 5, 0, 2, 6]\n",
      "[3, 1, 6, 2, 5, 7, 0, 4]\n",
      "[3, 1, 6, 2, 5, 7, 4, 0]\n",
      "[3, 1, 6, 4, 0, 7, 5, 2]\n",
      "[3, 1, 7, 4, 6, 0, 2, 5]\n",
      "[3, 1, 7, 5, 0, 2, 4, 6]\n",
      "[3, 5, 0, 4, 1, 7, 2, 6]\n",
      "[3, 5, 7, 1, 6, 0, 2, 4]\n",
      "[3, 5, 7, 2, 0, 6, 4, 1]\n",
      "[3, 6, 0, 7, 4, 1, 5, 2]\n",
      "[3, 6, 2, 7, 1, 4, 0, 5]\n",
      "[3, 6, 4, 1, 5, 0, 2, 7]\n",
      "[3, 6, 4, 2, 0, 5, 7, 1]\n",
      "[3, 7, 0, 2, 5, 1, 6, 4]\n",
      "[3, 7, 0, 4, 6, 1, 5, 2]\n",
      "[3, 7, 4, 2, 0, 6, 1, 5]\n",
      "[4, 0, 3, 5, 7, 1, 6, 2]\n",
      "[4, 0, 7, 3, 1, 6, 2, 5]\n",
      "[4, 0, 7, 5, 2, 6, 1, 3]\n",
      "[4, 1, 3, 5, 7, 2, 0, 6]\n",
      "[4, 1, 3, 6, 2, 7, 5, 0]\n",
      "[4, 1, 5, 0, 6, 3, 7, 2]\n",
      "[4, 1, 7, 0, 3, 6, 2, 5]\n",
      "[4, 2, 0, 5, 7, 1, 3, 6]\n",
      "[4, 2, 0, 6, 1, 7, 5, 3]\n",
      "[4, 2, 7, 3, 6, 0, 5, 1]\n",
      "[4, 6, 0, 2, 7, 5, 3, 1]\n",
      "[4, 6, 0, 3, 1, 7, 5, 2]\n",
      "[4, 6, 1, 3, 7, 0, 2, 5]\n",
      "[4, 6, 1, 5, 2, 0, 3, 7]\n",
      "[4, 6, 1, 5, 2, 0, 7, 3]\n",
      "[4, 6, 3, 0, 2, 7, 5, 1]\n",
      "[4, 7, 3, 0, 2, 5, 1, 6]\n",
      "[4, 7, 3, 0, 6, 1, 5, 2]\n",
      "[5, 0, 4, 1, 7, 2, 6, 3]\n",
      "[5, 1, 6, 0, 2, 4, 7, 3]\n",
      "[5, 1, 6, 0, 3, 7, 4, 2]\n",
      "[5, 2, 0, 6, 4, 7, 1, 3]\n",
      "[5, 2, 0, 7, 3, 1, 6, 4]\n",
      "[5, 2, 0, 7, 4, 1, 3, 6]\n",
      "[5, 2, 4, 6, 0, 3, 1, 7]\n",
      "[5, 2, 4, 7, 0, 3, 1, 6]\n",
      "[5, 2, 6, 1, 3, 7, 0, 4]\n",
      "[5, 2, 6, 1, 7, 4, 0, 3]\n",
      "[5, 2, 6, 3, 0, 7, 1, 4]\n",
      "[5, 3, 0, 4, 7, 1, 6, 2]\n",
      "[5, 3, 1, 7, 4, 6, 0, 2]\n",
      "[5, 3, 6, 0, 2, 4, 1, 7]\n",
      "[5, 3, 6, 0, 7, 1, 4, 2]\n",
      "[5, 7, 1, 3, 0, 6, 4, 2]\n",
      "[6, 0, 2, 7, 5, 3, 1, 4]\n",
      "[6, 1, 3, 0, 7, 4, 2, 5]\n",
      "[6, 1, 5, 2, 0, 3, 7, 4]\n",
      "[6, 2, 0, 5, 7, 4, 1, 3]\n",
      "[6, 2, 7, 1, 4, 0, 5, 3]\n",
      "[6, 3, 1, 4, 7, 0, 2, 5]\n",
      "[6, 3, 1, 7, 5, 0, 2, 4]\n",
      "[6, 4, 2, 0, 5, 7, 1, 3]\n",
      "[7, 1, 3, 0, 6, 4, 2, 5]\n",
      "[7, 1, 4, 2, 0, 6, 3, 5]\n",
      "[7, 2, 0, 5, 1, 4, 6, 3]\n",
      "[7, 3, 0, 2, 5, 1, 6, 4]\n"
     ]
    }
   ],
   "source": [
    "def queen(A, cur=0):\n",
    "    if cur == len(A):\n",
    "        print(A)\n",
    "        return 0\n",
    "    for col in range(len(A)):\n",
    "        A[cur], flag = col, True\n",
    "        for row in range(cur):\n",
    "            if A[row] == col or abs(col - A[row]) == cur - row:\n",
    "                flag = False\n",
    "                break\n",
    "        if flag:\n",
    "            queen(A, cur+1)\n",
    "queen([None]*8)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 参考\n",
    "1. https://zhuanlan.zhihu.com/p/42586566\n",
    "2. https://blog.51cto.com/853056088/2171435"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  },
  "toc": {
   "base_numbering": 1,
   "nav_menu": {},
   "number_sections": true,
   "sideBar": true,
   "skip_h1_title": false,
   "title_cell": "Table of Contents",
   "title_sidebar": "Contents",
   "toc_cell": false,
   "toc_position": {},
   "toc_section_display": true,
   "toc_window_display": true
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
